import React, {
  FC,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { Input, List, Spin } from 'antd';
import './customSiderList.less';
import { useControllableValue } from 'ahooks';
const { Item } = List;
const { Search } = Input;

interface ItemProp {
  name: string;
  id: string | number;
  [key: string]: any;
}

interface Props {
  list: ItemProp[];
  onSelect?(item: ItemProp): void;
  showAll?: boolean;
  loading?: boolean;
  placeholder?: string;
  emptyText?: string;
  activeItem?: ItemProp | null;
}

export const useListSelect = <T extends {}>() => {
  const [item, setItem] = useState<T | null>(null);

  const select = useCallback((item: T) => {
    setItem(item);
  }, []);

  return [item, select] as const;
};

const CustomSiderList: FC<Props> = (props) => {
  const { list, showAll, loading = false, placeholder, emptyText } = props;
  const [searchVal, setSearchVal] = useState('');
  const isFirstEnter = useRef(true);
  const [activeItem, setActiveItem] = useControllableValue<ItemProp>(props, {
    valuePropName: 'activeItem',
    trigger: 'onSelect',
  });

  const filterList = useMemo(() => {
    return list.filter((item) => item.name?.includes(searchVal));
  }, [list, searchVal]);

  useEffect(() => {
    if (list.length > 0 && isFirstEnter.current) {
      isFirstEnter.current = false;
      if (showAll) {
        return setActiveItem({ id: '-1', name: '全部' });
      }
      if (activeItem === undefined) {
        setActiveItem(list[0]);
      }
    }
  }, [list, showAll, activeItem, setActiveItem]);

  const onSearch = (e: string) => {
    setSearchVal(e);
  };

  return (
    <div
      className="customSiderList"
      style={{ overflowY: 'auto', height: '100%' }}
    >
      <div style={{ margin: '10px 5px' }}>
        <Search
          allowClear
          placeholder={placeholder || '模糊查询'}
          onSearch={(val) => onSearch(val)}
          enterButton
        />
      </div>
      <Spin spinning={loading}>
        {filterList.length > 0 ? (
          <List style={{ height: 'calc(100% - 52px)', overflowY: 'auto' }}>
            {showAll && (
              <Item
                className={'-1' === activeItem?.id ? 'select' : ''}
                key={'-1'}
                onClick={() => setActiveItem({ id: '-1', name: '全部' })}
              >
                <span>全部</span>
              </Item>
            )}
            {filterList.map((item) => {
              return (
                <Item
                  className={item.id === activeItem?.id ? 'select' : ''}
                  key={item.id}
                  onClick={() => setActiveItem(item)}
                >
                  <span>{item.name}</span>
                </Item>
              );
            })}
          </List>
        ) : (
          <div style={{ textAlign: 'center', color: '#ccc' }}>
            {emptyText || '暂无数据'}
          </div>
        )}
      </Spin>
    </div>
  );
};

export default CustomSiderList;
